package com.collectplus.express.menu;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.collectplus.express.BaseFragment;
import com.collectplus.express.MainActivity;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppConfig;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppLogic;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.IdCardInfoBean;
import com.collectplus.express.model.UserBean;
import com.collectplus.express.parcel.ParcelMainActivity2;
import com.shouhuobao.bhi.coupon.CouponListActivity;
import com.shouhuobao.bhi.login.LoginActivity;
import com.shouhuobao.bhi.stamp.StampStoreActivity;
import com.shouhuobao.identity.AuthenticationActivity;

import droid.frame.activity.HandlerMgr;
import droid.frame.app.Callback;
import droid.frame.umeng.UMeng;

/**
 * 左侧栏、设置相关
 *
 * @author coffee<br>
 * 2015-6-18上午10:43:53
 */
public class MenuFragment extends BaseFragment implements OnClickListener {

    private ImageView mIconImg;
    private TextView mNameTv, mMobileTv, mHelp;
    private View mLoginOut;// 退出登录
    private TextView mDebugOrReleaseTV;

    private UserBean user;
    private String debugStr = "https://jk.shouhuobao.com/guoer-appserv/";
    private String coffeeStr = "http://10.100.0.29:8091/guoer-appserv/";

    protected void findViewById() {
        setContentView(R.layout.home_menu);
        super.findViewById();
        mIconImg = (ImageView) findViewById(R.id.menu_user_head);
        mIconImg.setOnClickListener(this);
        mNameTv = (TextView) findViewById(R.id.menu_user_name);
        mNameTv.setOnClickListener(this);
        mMobileTv = (TextView) findViewById(R.id.menu_user_mobile);
        mHelp = (TextView) findViewById(R.id.menu_help_layout);
        mHelp.setOnClickListener(this);
        findViewById(R.id.menu_my_parcel_layout).setOnClickListener(this);
        findViewById(R.id.menu_about_layout).setOnClickListener(this);
        findViewById(R.id.menu_feedback_layout).setOnClickListener(this);
        findViewById(R.id.menu_help_layout).setOnClickListener(this);
        findViewById(R.id.menu_service_layout).setOnClickListener(this);
        findViewById(R.id.menu_coupon_layout).setOnClickListener(this);
        findViewById(R.id.menu_self_edit_name).setOnClickListener(this);
        findViewById(R.id.menu_personal_layout).setOnClickListener(this);
        findViewById(R.id.menu_coupon_store_layout).setOnClickListener(this);
        //身份验证
        findViewById(R.id.menu_authentication_layout).setOnClickListener(this);
        //选择测试服务器或正式服务器
        mDebugOrReleaseTV = (TextView) findViewById(R.id.debug_or_release_tv);
        mDebugOrReleaseTV.setOnClickListener(this);
//        debug();
        mLoginOut = findViewById(R.id.menu_exit_login);
        mLoginOut.setOnClickListener(this);
        findViewById(R.id.menu_phone_icon).setOnClickListener(this);
    }

    private void debug() {
        if (AppConfig.isTest) {
            mDebugOrReleaseTV.setVisibility(View.GONE);
            if (AppConfig.defaultService == 0) {
                AppConfig.isTest = true;
                mDebugOrReleaseTV.setText("测试地址");
                AppConfig.SERVER_URL_test = debugStr;
            } else if (AppConfig.defaultService == 1) {
                mDebugOrReleaseTV.setText("正式地址");
                AppConfig.isTest = false;
            } else {
                AppConfig.isTest = true;
                mDebugOrReleaseTV.setText("私人电脑");
                AppConfig.SERVER_URL_test = coffeeStr;
            }
        } else {
            mDebugOrReleaseTV.setVisibility(View.GONE);
        }
    }

    @SuppressLint("WrongConstant")
    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            //选择测试服务器或正式服务器
            case R.id.debug_or_release_tv:
                View view = LayoutInflater.from(getActivityContext()).inflate(R.layout.layout_debug_or_release, null);
                PopupWindow popupWindow = DialogMgr.createPopupWindow(getActivityContext(), view);
                popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
                popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                popupWindow.showAtLocation(findViewById(R.id.menu_exit_login), Gravity.RIGHT | Gravity.BOTTOM, 0, 0);
                popupWindowView(view, popupWindow);
                break;
            case R.id.menu_user_head:// 头像登陆
            case R.id.menu_user_name:// 用户名登陆
            case R.id.menu_personal_layout:// 跳转到个人中心
                if (user == null || isLogin() == false) {
                    startActivity(new Intent(getActivityContext(), LoginActivity.class));
                } else {
                    intent = new Intent();
                    intent.putExtra("name", user.getName());
                    intent.setClass(getActivityContext(), PersonalCenterActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.menu_service_layout:// 服务范围
                intent = new Intent();
                intent.setClass(getActivityContext(), WebViewActivity.class);
                intent.putExtra("title", "服务范围");
                startActivity(intent);
                break;
            case R.id.menu_self_edit_name:// 开具发票
                intent = new Intent();
                intent.setClass(getActivityContext(), WebViewActivity.class);
                intent.putExtra("title", "开具发票");
                startActivity(intent);
                break;
            case R.id.menu_coupon_store_layout:// 邮票商城
                if (user == null || isLogin() == false) {
                    startActivity(new Intent(getActivityContext(), LoginActivity.class));
                } else {
                    UMeng.click(getActivityContext(), "menu_stamp_shop_click");
                    startActivityWhenLogin(StampStoreActivity.class);
                }
                break;
            case R.id.menu_coupon_layout:// 邮票
                UMeng.click(getActivityContext(), "menu_my_stamp_click");
                startActivityWhenLogin(CouponListActivity.class);
                break;
            case R.id.menu_about_layout:// 关于我们
                UMeng.click(getActivityContext(), "menu_about_click");
                startActivity(new Intent(getActivityContext(), AboutActivity.class));
                break;
            case R.id.menu_feedback_layout:// 意见反馈
                UMeng.click(getActivityContext(), "menu_feedback_click");
                startActivityWhenLogin(FaqActivity.class);
                break;
            case R.id.menu_help_layout:// 使用帮助
                intent = new Intent();
                intent.setClass(getActivityContext(), WebViewActivity.class);
                intent.putExtra("title", "帮助中心");
                startActivity(intent);
                break;
            case R.id.menu_exit_login:// 退出登录
                DialogMgr.showQuit(getActivityContext(), new Callback() {
                    public void onDialogDismiss() {
                        HandlerMgr.sendMessage(MsgID.logout, null);
                        // 清空信息
                        AppCache.onLogout();
                        updateViewData();//
                        AppHttp.getInstance().getAppConfig(getActivityContext());
                        // 调到登录界面
                        startActivity(LoginActivity.class);
                    }
                });
                break;
            case R.id.menu_phone_icon:// 联系我们
                UMeng.click(getActivityContext(), "home_left_contact_us_click");
                DialogMgr.showPhoneDialog(getActivityContext(), null);
                break;
            case R.id.menu_authentication_layout://身份验证
                if (user == null || isLogin() == false) {
                    startActivity(new Intent(getActivityContext(), LoginActivity.class));
                } else {
                    UMeng.click(getActivityContext(), "menu_authentication_click");
                    IdCardInfoBean bean = AppCache.getCardInfoBean();
                    if (null != bean) {
                        startActivityWhenLogin(AuthenticationActivity.class);
                    } else {
                        showLoadingDialog(null);
                        AppHttp.getInstance().queryIDCardInfo(0);
                    }
                }
                break;
            //我的包裹
            case R.id.menu_my_parcel_layout:
                UMeng.click(getActivityContext(), "home_myParcel_click");
                startActivityWhenLogin(ParcelMainActivity2.class);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        updateViewData();
        if (MainActivity.getInstance().isFromBackground()) {
            if (user != null && user.getId() != 0) {
                AppHttp.getInstance().profile();
            }
        }
    }

    public void openDrawer() {
        // Umeng.onResume(TAG, getActivityContext());
        updateViewData();
    }

    private void updateViewData() {
        user = AppCache.getUser();
        // 未登录
        if (user == null || isLogin() == false) {
            mIconImg.setImageResource(R.drawable.user_head_default);
            mNameTv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            mNameTv.setText("点击登录");
            mNameTv.setVisibility(View.VISIBLE);
            //
            mMobileTv.setVisibility(View.GONE);
            mLoginOut.setVisibility(View.GONE);
        } else {// 用户已登录
            mIconImg.setImageResource(R.drawable.user_head_login);
            mNameTv.setText(user.getName());
            mMobileTv.setText(user.getPhone());
            mMobileTv.setVisibility(View.VISIBLE);
            mLoginOut.setVisibility(View.VISIBLE);
        }
    }

    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.profile:
                AppResult<UserBean> result = JSON.parser(msg.obj, UserBean.class);
                if (result.isSuccess()) {
                    user = result.getResult();
                    if (user == null) {
                        android.util.Log.e("user", "");
                    } else {
                        AppCache.setUser(user);
                        if (getActivityContext() != null) {
                            getActivityContext().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    updateViewData();
                                }
                            });
                        }
                    }
                } else {
                    // ignore
                }
                return true;
            case MsgID.query_idCard_info:
                cancelLoadingDialog();
                if (0 != msg.arg1) {
                    return false;
                }
                final AppResult<IdCardInfoBean> appResult = JSON.parser(msg.obj, IdCardInfoBean.class);
                getActivityContext().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (appResult.isSuccess()) {
                            AppLogic.contextToAuthenticationClass(getActivityContext(), appResult.getResult());
                        } else {
                            showToast(appResult.getMessage());
                        }
                    }
                });
                return false;
            default:
                return super.handleMessage(msg);
        }
    }

    /**
     * 更新popupwindow状态和显示
     *
     * @param view
     * @param popupWindow
     */
    private void popupWindowView(View view, final PopupWindow popupWindow) {
        //关闭按钮
        ImageView closeIV = (ImageView) view.findViewById(R.id.title_right);
        //测试地址
        final TextView debugTV = (TextView) view.findViewById(R.id.debug_TV);
        //正式地址
        TextView releaseTV = (TextView) view.findViewById(R.id.release_TV);
        //咖啡电脑
        TextView coffeeTV = (TextView) view.findViewById(R.id.coffee_TV);
        //测试地址
        debugTV.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                AppConfig.isTest = true;
                AppConfig.defaultService = 0;
                AppConfig.SERVER_URL_test = debugStr;
                mDebugOrReleaseTV.setText("测试地址");
                popupWindow.dismiss();
            }
        });
        //正式地址
        releaseTV.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                AppConfig.isTest = false;
                AppConfig.defaultService = 1;
                mDebugOrReleaseTV.setText("正式地址");
                popupWindow.dismiss();
            }
        });
        //咖啡电脑
        coffeeTV.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                AppConfig.isTest = true;
                AppConfig.defaultService = 2;
                AppConfig.SERVER_URL_test = coffeeStr;
                mDebugOrReleaseTV.setText("私人电脑");
                popupWindow.dismiss();
            }
        });
        closeIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

}